/* eslint-disable @typescript-eslint/no-explicit-any */
import { message } from 'ant-design-vue';

export type IRes = {
    data?: unknown;
    [propName: string]: any;
};

export const errorHandler = (error: unknown, eventName?: string) => {
    console.log(error, eventName ? eventName : '');
    if (typeof error === 'string') {
        message.error(error);
        return;
    }
    const _error = error as { message: string };
    if (!_error?.message || _error?.message.includes('timeout of 20000ms exceeded')) {
        return;
    }
    message.error(_error?.message);
};

export function isValidRes<T extends IRes>(res: T) {
    if (!res) return false;
    if (res?.status?.code !== 200) return;
    return true;
}

type validStatusType = (status: StatusType | undefined) => void;
export const validStatus: validStatusType = (status = { desc: '请求失败' }) => {
    if (status?.code !== 200) {
        throw status?.desc;
    }
};

interface Permission {
    permissionKey: string;
    permissionName: string;
    children?: Permission[];
}

export function hasPermissionKey(permissions: Permission[], key: string): boolean {
    if (!Array.isArray(permissions)) {
        return false;
    }
    for (const permission of permissions) {
        if (permission.permissionKey === key) {
            return true;
        }
        if (permission.children && hasPermissionKey(permission.children, key)) {
            return true;
        }
    }
    return false;
}
